package java_thinking.unit_16;

import java.lang.reflect.Field;

/**
 * @Desc:   反射获取对象field
 * @author: cww
 * @DateTime: 2019/4/10 9:46
 */

public class FieldDemo {
    public static void main(String[] args) {
        SampleClass sampleClass = new SampleClass();
        try {
            Field field = SampleClass.class.getField("sampleField");
            System.out.println(field.getLong(sampleClass));
            //如果不进行Accessible设置，该字段是private会抛出java.lang.NoSuchFieldException: sampleField异常
            //另外如果field是私有的，上面需要使用getDeclaredField()
            Field field1 = SampleClass.class.getDeclaredField("sampleField1");
            field1.setAccessible(true);
            System.out.println(field1.getLong(sampleClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class SampleClass {
    public static long sampleField = 5000;
    private static long sampleField1 = 1;
    private static long sampleField2 = 1;
}
